import requests
import re
from bs4 import BeautifulSoup
from utils.req import get_request

base_url = "https://www.mabtech.com"
headers = {
    "accept": "*/*",
    "accept-language": "zh-CN,zh;q=0.9",
    "cache-control": "no-cache",
    "pragma": "no-cache",
    "priority": "u=1, i",
    "referer": "https://www.mabtech.com/",
    "sec-ch-ua": '"Not)A;Brand";v="8", "Chromium";v="138", "Google Chrome";v="138"',
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": '"macOS"',
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-origin",
    "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36",
}

def convert_rem_to_px(html_content, rem_base=16):
    """
    将HTML内容中的rem单位转换为px单位
    
    参数:
        html_content: 包含rem单位的HTML内容字符串
        rem_base: 1rem对应的px值，默认为16px
    
    返回:
        转换后的HTML内容字符串
    """
    # 正则表达式匹配CSS中的rem单位值
    # 匹配类似: 1rem, 2.5rem, .5rem, 3rem; 等模式
    pattern = r'(\d*\.?\d+)\s*rem'
    
    def replace_match(match):
        """替换匹配到的rem值为px值"""
        rem_value = float(match.group(1))
        px_value = rem_value * rem_base
        # 如果是整数，直接转换为整数形式，否则保留小数
        return f"{int(px_value)}px" if px_value.is_integer() else f"{px_value}px"
    
    # 执行替换
    converted_content = re.sub(pattern, replace_match, html_content)
    return converted_content

def search_product(query):
    """
    搜索 Mabtech 网站的商品

    Args:
        query (str): 搜索关键词

    Returns:
        url:商品详情url
    """

    url = "https://www.mabtech.com/api/autocomplete"
    params = {"q": query}

    try:
        response = requests.get(url=url, headers=headers, params=params)
        response.raise_for_status()  # 检查请求是否成功
        res = response.json()
        if res:
            return base_url + res[0]["url"]
        return None

    except requests.exceptions.RequestException as e:
        print(f"请求发生错误: {e}")
        return None


def get_product_detail(url):
    """
    获取商品详情
    """
    response = get_request(url=url, headers=headers)
    soup = BeautifulSoup(response.text, "html.parser")
    return soup


def extract_product_detail(soup):
    """
    提取商品详情
    """
    description = soup.find("div", class_="css-bkma01")
    return str(description)


def process_product_detail(procode: str):
    """
    处理商品详情
    """
    if url := search_product(procode):
        response = get_request(url=url, headers=headers)
        soup = BeautifulSoup(response.text, "html.parser")
        if description := extract_product_detail(soup):
            return convert_rem_to_px(description)

    return None


if __name__ == "__main__":
    # 示例用法
    result = process_product_detail("4406-6-100")
    print(result)
